<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="140px">
      <el-form-item label="订单拥有者姓名" prop="orderOwnerName">
        <el-input
          v-model="queryParams.orderOwnerName"
          placeholder="请输入订单拥有者姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单拥有者手机号" prop="orderOwnerPhone">
        <el-input
          v-model="queryParams.orderOwnerPhone"
          placeholder="请输入订单拥有者手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:order:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:order:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:order:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:order:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="姓名" align="center" prop="orderOwnerName"/>
      <el-table-column label="手机号" align="center" prop="orderOwnerPhone"/>
      <el-table-column label="是否含早餐" align="center" prop="haveBreakfastName">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.yes_or_no" :value="scope.row.haveBreakfastName"/>
        </template>
      </el-table-column>
      <el-table-column label="房间单价" align="center" prop="roomPrice"/>
      <el-table-column label="预订天数" align="center" prop="orderRoomAmount"/>

      <el-table-column label="入住时间段" align="center" prop="checkInPeriod" width="300"/>
      <el-table-column label="支付状态" align="center" prop="payStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pay_state" :value="scope.row.payStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="房间名" align="center" prop="roomName"/>
      <el-table-column label="订单状态" align="center" prop="checkInStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_state" :value="scope.row.checkInStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:order:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:order:remove']"
          >删除
          </el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
            <span class="el-dropdown-link">
              <i class="el-icon-d-arrow-right el-icon--right"></i>更多
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="ruzhu" icon="el-icon-circle-check" :disabled="scope.row.checkInStatus!=='1'"
                                v-hasPermi="['system:role:ruzhu']">入住
              </el-dropdown-item>
              <el-dropdown-item command="tuifang" icon="el-icon-user" :disabled="scope.row.checkInStatus!=='2'"
                                v-hasPermi="['system:role:tuifang']">退房
              </el-dropdown-item>
              <el-dropdown-item command="quxiao" icon="el-icon-user" :disabled="scope.row.checkInStatus!=='1'"
                                v-hasPermi="['system:role:cancel']">取消
              </el-dropdown-item>
              <el-dropdown-item command="fapiao" icon="el-icon-user" :disabled="scope.row.checkInStatus!=='3'"
                                v-hasPermi="['system:role:create']">生成发票
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="160px">
        <el-form-item label="订单拥有者姓名" prop="orderOwnerName">
          <el-input v-model="form.orderOwnerName" placeholder="请输入订单拥有者姓名"/>
        </el-form-item>
        <el-form-item label="订单拥有者手机号" prop="orderOwnerPhone">
          <el-input v-model="form.orderOwnerPhone" placeholder="请输入订单拥有者手机号"/>
        </el-form-item>
        <el-form-item label="是否是会员" prop="isMember">
          <el-switch
            v-model="isMember"
            active-value=1
            inactive-value=0
            active-text="会员"
            inactive-text="非会员">
          </el-switch>
        </el-form-item>
        <el-form-item label="房间类型" prop="roomTypeName">
          <el-select v-model="form.roomTypeName" placeholder="请选择房间类型" style="width: 100%" @change="handleType">
            <el-option v-for="(item,index) in names" :key="item.id" :label="item.roomTypeName"
                       :value="item.roomTypeName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房间名" prop="roomName">
          <el-select v-model="form.roomName" placeholder="请选择房间" style="width: 100%" @change="handleRoom">
            <el-option v-for="(item,index) in roomnames" :key="item.id" :label="item.roomName"
                       :value="item.roomName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否含早餐" prop="haveBreakfastName">
          <el-switch
            v-model="form.haveBreakfastName"
            active-value=1
            inactive-value=0
            active-text="含早餐"
            inactive-text="不含早餐">
          </el-switch>
        </el-form-item>
        <el-form-item label="房间单价" prop="roomPrice">
          <el-input v-model="form.roomPrice" placeholder="请输入房间单价"/>
        </el-form-item>
        <el-form-item label="预订天数" prop="orderRoomAmount">
          <el-input-number v-model="form.orderRoomAmount" placeholder="请输入预订天数" :min="1" :max="10"
                           @change="computeTotal"></el-input-number>
        </el-form-item>
        <!--<el-form-item label="入住时间段" prop="checkInPeriod">
          <el-input v-model="form.checkInPeriod" placeholder="请输入入住时间段"/>
        </el-form-item>-->
        <el-form-item label="入住时间段" prop="checkInPeriod">
          <el-date-picker
            v-model="form.checkInPeriod"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <div style="padding-left: 150px;">
          <span style="color: brown;font-size: 10px" v-if="this.isMember==='1'">该顾客是会员用户，享受9折优惠</span>
        </div>
        <el-form-item label="总金额" prop="totalMoney">
          <el-input v-model="form.totalMoney" placeholder="总金额"></el-input>
        </el-form-item>
        <el-form-item label="是否入住" prop="checkInStatus">
          <el-switch
            v-model="form.checkInStatus"
            active-value=2
            inactive-value=1
            active-text="入住"
            inactive-text="不入住">
          </el-switch>
        </el-form-item>
        <el-form-item
          v-for="(domain, index) in domains"
          :label="'入住人' + (index+1 )"
          :key="domain.key"
        >
          <el-input v-model="domain.peopleName" placeholder="请输入入住人姓名"></el-input>
          <el-input v-model="domain.idNumber" placeholder="请输入入住人身份证号码"></el-input>
          <el-button @click.prevent="removeDomain(domain)">删除</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="addDomain">新增入住人</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog
      title="办理入住"
      :visible.sync="ruzhudialog"
      width="30%">
      <el-form ref="form" :model="form" :rules="rules" label-width="160px">
        <el-form-item label="订单拥有者姓名" prop="orderOwnerName">
          <el-input v-model="form.orderOwnerName" placeholder="请输入订单拥有者姓名"/>
        </el-form-item>
        <el-form-item label="订单拥有者手机号" prop="orderOwnerPhone">
          <el-input v-model="form.orderOwnerPhone" placeholder="请输入订单拥有者手机号"/>
        </el-form-item>
        <el-form-item label="房型名称" prop="roomTypeName">
          <el-input v-model="form.roomTypeName" placeholder="请输入房型名称"/>
        </el-form-item>
        <el-form-item label="入住时间段" prop="checkInPeriod">
          <el-input v-model="form.checkInPeriod" placeholder="请输入入住时间段"/>
        </el-form-item>
        <el-form-item
          v-for="(domain, index) in domains"
          :label="'入住人' + (index+1 )"
          :key="domain.key"
        >
          <el-input v-model="domain.peopleName" placeholder="请输入入住人姓名"></el-input>
          <el-input v-model="domain.idNumber" placeholder="请输入入住人身份证号码"></el-input>
          <el-button @click.prevent="removeDomain(domain)">删除</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit()">提交</el-button>
          <el-button @click="addDomain">新增入住人</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import { listOrder, getOrder, delOrder, addOrder, updateOrder, tuifang, quxiao, ruzhu } from '@/api/hotel/order'
  import { listName } from '@/api/hotel/type'
  import { addInfo } from '@/api/hotel/info'
  import { listRoomName, listRoomInfo } from '@/api/hotel/room'
  import { listSelect } from '@/api/system/user'

  export default {
    dicts: ['pay_state', 'order_state', 'yes_or_no'],
    name: 'Order',
    data() {
      return {
        names: [],
        domains: [{
          peopleName: '',
          idNumber: '',
          id: '',
          orderId: ''
        }],
        userParams: {
          userType: '11'
        },
        ruzhudialog: false,
        userList: [],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 订单信息表格数据
        orderList: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          orderNumber: null,
          orderName: null,
          orderOwnerName: null,
          orderOwnerPhone: null,
          roomTypeName: null,
          bedType: null,
          haveBreakfastName: null,
          roomPrice: null,
          orderRoomAmount: null,
          expectArriveTime: null,
          checkInPeriod: null,
          payStatus: null,
          roomName: null,
          checkInStatus: null,
          totalMoney: null
        },
        isMember: 0,
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        roomnames: [],
        room: {},
        fapiaoForm: {}
      }
    },
    created() {
      this.getList ()
      this.listNames ()
      this.listUser ()
    },
    methods: {
      handleRoom(data) {
        listRoomInfo (data).then (res => {
          this.room = res.data
          this.form.roomPrice = this.room.roomPrice
          this.form.haveBreakfastName = this.room.haveBreakfast
          this.form.totalMoney = this.form.roomPrice
        })
      },
      handleType(data) {
        listRoomName (data).then (res => {
          this.roomnames = res.list
        })
      },

      listNames() {
        listName ().then (res => {
          this.names = res.list
        })
      },

      listUser() {
        listSelect (this.userParams).then (res => {
          this.userList = res.list
        })
      },
      /** 查询订单信息列表 */
      getList() {
        this.loading = true
        listOrder (this.queryParams).then (response => {
          this.orderList = response.rows
          this.total = response.total
          this.loading = false
        })
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset ()
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          orderNumber: null,
          orderName: null,
          orderOwnerName: null,
          orderOwnerPhone: null,
          roomTypeName: null,
          bedType: null,
          haveBreakfastName: null,
          roomPrice: null,
          orderRoomAmount: null,
          expectArriveTime: null,
          checkInPeriod: null,
          createTime: null,
          payStatus: '0',
          roomName: null,
          checkInStatus: '0'
        }
        this.isMember = 0
        this.resetForm ('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList ()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm ('queryForm')
        this.handleQuery ()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map (item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset ()
        this.listNames ()
        this.listUser ()
        this.domains = [{
          peopleName: '',
          idNumber: '',
          id: '',
          orderId: ''
        }]
        this.open = true
        this.title = '添加订单信息'
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset ()
        const id = row.id || this.ids
        this.listNames ()
        this.listUser ()
        this.domains = [{
          peopleName: '',
          idNumber: '',
          id: '',
          orderId: ''
        }]
        getOrder (id).then (response => {
          this.form = response.data
          this.domains = this.form.peopleInfos === null?[{
            peopleName: '',
            idNumber: '',
            id: '',
            orderId: ''
          }]:this.form.peopleInfos
          this.form.checkInPeriod = this.form.checkInPeriod.split ('到')
          console.log(this.domains)
          console.log(this.form.peopleInfos)
          this.open = true
          this.title = '修改订单信息'
        })

      },
      /** 提交按钮 */
      submitForm() {
        this.form.payStatus = 1
        this.form.peopleInfos = this.domains
        this.form.checkInPeriod = this.form.checkInPeriod.join ('到')
        // this.form.checkInStatus = 2
        this.$refs[ 'form' ].validate (valid => {
          if ( valid ) {
            if ( this.form.id != null ) {
              updateOrder (this.form).then (response => {
                this.$modal.msgSuccess ('修改成功')
                this.open = false
                this.getList ()
              })
            } else {
              addOrder (this.form).then (response => {
                this.$modal.msgSuccess ('新增成功')
                this.open = false
                this.getList ()
              })
            }
            this.domains = [{
              peopleName: '',
              idNumber: ''
            }]
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids
        this.$modal.confirm ('是否确认删除订单信息编号为"' + ids + '"的数据项？').then (function() {
          return delOrder (ids)
        }).then (() => {
          this.getList ()
          this.$modal.msgSuccess ('删除成功')
        }).catch (() => {
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download ('system/order/export', {
          ... this.queryParams
        }, `order_${new Date ().getTime ()}.xlsx`)
      },
      // 更多操作触发
      handleCommand(command, row) {
        switch ( command ) {
          case 'ruzhu':
            this.ruzhu (row)
            break
          case 'tuifang':
            this.tuifang (row)
            break
          case 'quxiao':
            this.quxiao (row)
            break
          case 'fapiao':
            this.fapiao (row)
            break
          default:
            break
        }
      },

      fapiao(rowDate) {
        console.log (rowDate)
        this.fapiaoForm.money = rowDate.totalMoney
        this.fapiaoForm.orderId = rowDate.id
        this.fapiaoForm.orderName = rowDate.orderOwnerName
        addInfo (this.fapiaoForm).then (res => {
          this.$modal.msgSuccess ('生成发票成功')
          this.open = false
          this.getList ()
        })
      },
      ruzhu(row) {
        this.form = row
        this.ruzhudialog = true
      },
      tuifang(row) {
        this.form.id = row.id
        this.form.checkInStatus = '3'
        this.$confirm ('确定要退房吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then (() => {
          tuifang (this.form).then (response => {
            this.$modal.msgSuccess ('退房成功')
            this.getList ()
          })
        }).catch (() => {
          this.$message ({
            type: 'info',
            message: '退房失败'
          })
        })

      },
      quxiao(row) {
        let dateTime = row.checkInPeriod
        let startDate = dateTime.split ('到')[ 0 ]
        // new Date(startDate).getTime()
        let start = new Date (startDate).getTime ()
        let nowDate = new Date ().getTime ()
        if ( start - nowDate < 2 * 3600 * 1000 ) {
          this.$message ({
            type: 'info',
            message: '距离入住时间2小时之内不能取消订单'
          })
        } else {
          quxiao (row.id)
        }
      },
      submit() {
        /*for ( let i = 0; i < this.domains.length; i++ ) {
          if ( this.domains[ i ].peopleName !== '' ) {
            this.form.peopleName += this.domains[ i ].peopleName + ','
          }
          if ( this.domains[ i ].idNumber !== '' ) {
            this.form.idNumber += this.domains[ i ].idNumber + ','
          }
        }
        if(this.form.peopleName!==""){
          this.form.peopleName = this.form.peopleName.substr(0,this.form.peopleName.length-1)
        }
        if(this.form.idNumber!==""){
          this.form.idNumber = this.form.idNumber.substr(0,this.form.idNumber.length-1)
        }*/
        this.form.peopleInfos = this.domains
        this.form.checkInStatus = '2'
        ruzhu (this.form).then (response => {
          this.$modal.msgSuccess ('入住成功')
          this.ruzhudialog = false
          this.getList ()
          this.domains = [{
            peopleName: '',
            idNumber: ''
          }]
        })

      },

      removeDomain(item) {
        var index = this.domains.indexOf (item)
        if ( index !== -1 ) {
          this.domains.splice (index, 1)
        }
      },
      addDomain() {
        this.domains.push ({
          value: '',
          key: Date.now ()
        })
      },
      computeTotal(currentValue, oldValue) {
        if ( this.isMember === 1 ) {
          this.form.totalMoney = this.form.roomPrice * currentValue * 0.9
        } else {
          this.form.totalMoney = this.form.roomPrice * currentValue
        }

      }

    }
  }
</script>
